package com.yishusmt.wechatapi.wechatdev.controller;

import com.yishusmt.wechatapi.wechatdev.constant.WeChatConstant;
import com.yishusmt.wechatapi.wechatdev.dto.base.Result;
import com.yishusmt.wechatapi.wechatdev.utils.Sha1Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 验证token
 *
 * @author zhangyi
 * @date 2018/8/27 15:51
 */
@Slf4j
@Controller
@Api(description = "微信验证access_token")
public class VerificationTokenController {


    @GetMapping("/")
    @ResponseBody
    @ApiOperation(value = "验证token",httpMethod = "GET")
    public String token(HttpServletRequest request){
        Map<String,String> wechat = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        String[] check = new String[WeChatConstant.PARAMETER_SIZE];
        StringBuffer stringBuffer = new StringBuffer();
        check[0] = WeChatConstant.TOKEN;
        int index = 1;
        while(parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            if (WeChatConstant.TIMESTAMP.equals(key) || WeChatConstant.NONCE.equals(key)){
                check[index++] = value;
            }
            wechat.put(key,value);
        }
        //检查数组
        Arrays.asList(check).stream().forEach(e -> {
            System.out.println("参数： "+e);
            if(e == null){
                log.error("微信传入参数为空！！！");
                return;
            }
        });
        //字典排序
        Arrays.sort(check);
        //连接字符串
        Arrays.asList(check).stream().forEach(e -> stringBuffer.append(e));
        //sha1加密
        String encode = Sha1Util.encode(stringBuffer.toString());
        //验证判断
        if(encode.equals(wechat.get(WeChatConstant.SIGNATURE))){
            log.info("微信验证成功！");
            return wechat.get(WeChatConstant.ECHOSTR);
        }else{
            log.info("微信验证失败！");
            return null;
        }
    }
}
